var express = require('express');
var router = express.Router();
const User = require('../models/user');
const Student = require('../models/student');
// const crypto = require('crypto');
const bcrypt = require('bcryptjs');

/* 查询所有用户. */
router.get('/', async(req, res) => {
  try {
    const users = await User.find()
      .select('name age mobile avatar')
    res.status(200);
    res.json(users);
  } catch (err) {
    res.status(500);
    res.json(err);
  }
});

/* 查询某个用户. */
router.get('/detail/:id', async(req, res) => {
  try {
    const user = await User.findOne({_id: req.params.id})
    res.status(200);
    res.json(user);
  } catch (err) {
    res.status(500);
    res.json(err);
  }
});

//新增用户/用户注册
router.post('/create', async(req, res) => {
  try {
    //用户密码加密
    //生成随机盐值
    // const salt = crypto.randomBytes(16).toString('hex');
    // const derivedKey = crypto.pbkdf2Sync(req.body.user.password, salt, 100000, 64, 'sha512');
    // 使用derivedKey作为加密后的密码或进一步处理
    // req.body.user.password = salt + ":" + derivedKey.toString('hex');
    const salt = bcrypt.genSaltSync(10);
    const hash = bcrypt.hashSync(req.body.user.password, salt);
    req.body.user.password = hash;
  
    const user = await User.create(req.body.user);
    res.status(200);
    res.json({
      result: true,
      message: "新增成功"
    });
  } catch (err) {
    res.status(500);
    res.json(err);
  }
});

//用户登录
router.post('/login', async(req, res) => {
  try {
    const user = await User.findOne({name: req.body.user.name});
    if (!user) {
      res.status(200);
      res.json({
        result: false,
        message: "用户名不存在"
      });
    } else {
      // const [salt, key] = user.password.split(":");
      // const derivedKey = crypto.pbkdf2Sync(req.body.user.password, salt, 100000, 64, 'sha512');
      const match = bcrypt.compareSync(req.body.user.password, user.password)
      // if (derivedKey.toString('hex') == key) {
      if (match) {
        const student = await Student.findOne({user: user._id}).populate({path: "courses"});
        res.status(200);
        res.json({
          result: true,
          message: "登录成功",
          student: student
        });
      } else {
        res.status(200);
        res.json({
          result: false,
          message: "密码错误"
        });
      }
    }
  } catch (err) {
    res.status(500);
    res.json(err);
  }
});

router.post('/delete', async(req, res) => {
  try {
    const user = await User.findByIdAndDelete({_id: req.body.user._id});
    res.status(200);
    res.json({
      result: true,
      message: "删除成功",
      user: user
    });
  } catch (err) {
    res.status(500);
    res.json(err);
  }
});

router.post('/update', async(req, res) => {
  try {
    const user = await User.findByIdAndUpdate({_id: req.body.user._id}, req.body.user);
    res.status(200);
    res.json({
      result: true,
      message: "修改成功",
      user: user
    });
  } catch (err) {
    res.status(500);
    res.json(err);
  }
});

module.exports = router;

